package com.wang.demo.application.handler;

import com.wang.demo.protocol.message.LoginRequestMessage;
import com.wang.demo.protocol.message.LoginResponseMessage;
import com.wang.demo.service.UserService;
import com.wang.demo.service.factory.SessionFactory;
import com.wang.demo.service.factory.UserServiceFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author: Jeffrey
 * @date: 2022/01/21/9:38
 * @description:
 */
@ChannelHandler.Sharable
public class LoginHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    /**
     * @param ctx 流水线channel 上下文
     * @param msg 登录请求消息
     * @throws Exception e
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();

        UserService userService = UserServiceFactory.getUserService();
        boolean login = userService.login(username, password);
        if (login){
            /*登录成功，绑定会话*/
            SessionFactory.getSession().bind(ctx.channel(),username);
            LoginResponseMessage responseMessage =new LoginResponseMessage(true,"登录成功");
            ctx.writeAndFlush(responseMessage);
        }else{
            LoginResponseMessage message = new LoginResponseMessage(false, "登录失败！");
            ctx.writeAndFlush(message);
        }
    }
}
